﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CuteAnt;
using CuteAnt.Log;
using CuteAnt.OrmLite.DataAccessLayer;

namespace XiaoMIDataTran
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void button1_Click(object sender, EventArgs e)
		{
			// 测试数据库：http://pan.baidu.com/s/1bn8fPX9
			//             下载完毕，解压到执行目录 Data目录下

			DAL.ShowSQL = false;

			var factory = xiaomi.Meta.ShardingProviderFactory;

			var count = xiaomi.Meta.Count;
			MessageBox.Show("小米数据库记录总数：" + count);
			var batchSize = 200000;
			var index = 0L;
			var sw = new Stopwatch();

			sw.Start();
			HmTrace.WriteWarn("开始迁移小米数据库......");

			var useBulkCopy = true;
			if (useBulkCopy)
			{
				while (true)
				{
					var size = (Int32)Math.Min(batchSize, count - index);
					if (size <= 0) { break; }

					var ds = xiaomi.FindAllDataSet(null, xiaomi._.ID.Asc(), null, index, size);
					if (ds == null || ds.Tables.Count <= 0) { break; }
					var dt = ds.Tables[0];
					var rowcount = dt.Rows.Count;
					if (rowcount <= 0) { break; }
					index += rowcount;

					using (var sharding = new XiaoMIShard("MsSql")) // Config/DbProvider.config中的 DbProvider
					{
						// 数据库名称、表名称
						sharding.Startup("xiaomi", "xiaomiA");
						xiaomi.TransformAll(dt, true);
					}
				}
			}
			else
			{
				while (true)
				{
					var size = (Int32)Math.Min(batchSize, count - index);
					if (size <= 0) { break; }

					var list = xiaomi.FindAll(null, xiaomi._.ID.Asc(), null, index, size);
					if (list.Count <= 0) { break; }
					index += list.Count;

					using (var sharding = new XiaoMIShard("MsSql")) // Config/DbProvider.config中的 DbProvider
					{
						// 数据库名称、表名称
						sharding.Startup("xiaomi", "xiaomi");
						xiaomi.TransformAll(list, true, 20);
					}
				}
			}

			sw.Stop();

			HmTrace.WriteWarn("迁移小米数据库：{0} 条完成，耗时：{1}毫秒。", count, sw.ElapsedMilliseconds);

			MessageBox.Show("迁移小米数据库：{0} 条完成，耗时：{1}毫秒。".FormatWith(count, sw.ElapsedMilliseconds));
		}
	}
}
